import GraphLayout from '@/components/graphLayout';
import { useRequest } from '@umijs/hooks';
import ProCard from '@ant-design/pro-card';
import { Card, List, Tabs } from 'antd';
import { useEffect, useState } from 'react';
import AvatarList from './components/avatarList';
import ControlPowerList from './components/controlPowerList';
import EquityGraph from './components/graph';
import DemoPie from '../../ControlPower/Penetration/components/pie';
import RelationList from './components/RelationList';
import './style.css';

import { getEquityMsg, getEquityStruct } from '@/services/zhirong/equity';


const ComputeFinalHolders = (network) => {
  const { nodes, edges } = network;
  const finalHolders = nodes?.map((node) => {
    return {
      ...node,
      inDegree: 0,
      outDegree: 0,
    };
  });
  edges?.forEach((edge) => {
    finalHolders.forEach((node) => {
      if (node.id === edge.source) {
        node.outDegree += 1;
      }
      if (node.id === edge.target) {
        node.inDegree += 1;
      }
    });
  });
  return finalHolders?.filter((node) => node.inDegree === 0);
};

const Penetration = ({ enterprise, setEnterprise, date }) => {
  console.log('daddadad', enterprise)

  console.log('test', enterprise)
  const [holders, setHolders] = useState([]);
  // 存储控制权组件传来的信息
  const [controlData, setControlData] = useState();
  // 传给graph组件的参数，配合onChangePanel进行控制图的刷新
  const [network, setNetwork] = useState();
  const [controlHolders, setControlHolders] = useState([]);
  const [loading, setLoading] = useState(false);
  // true是股权网络的图，false是控制权的图
  const [isNetworkPanel, setPanelType] = useState(true);
  const [equityStructPieData, setEquityStructPieData] = useState([]);
  const [equityMsgData, setEquityMsgData] = useState([]);

  const handleUpdateNetwork = (network) => {
    setEnterprise({ ...enterprise, network });
  };
  /*   const handleUpdateEnterprise = (enterprise)=>{
      setEnterprise({ ...enterprise })
    } */
  const { run: runGetEquityStruct } = useRequest(getEquityStruct, {
    manual: true,
    onSuccess: (result) => {
      console.log("饼图", result);
      setEquityStructPieData(result.data)
    },
  });

  const { run: runGetEquityMsg } = useRequest(getEquityMsg, {
    manual: true,
    onSuccess: (result) => {
      setEquityMsgData(result.data)
    },
  });
  useEffect(() => {
    // console.log('enterprise changes>>>>>', enterprise, enterprise.network)
    const res = ComputeFinalHolders(enterprise.network || { node: [], edge: [] });
    if (res?.length != 0) {
      setHolders(res);
    }
    runGetEquityStruct({
      centerId: enterprise.eid,
    });
    runGetEquityMsg({
      centerId: enterprise.eid,
    })
  }, [enterprise.network, network, enterprise]);

  const onChangePanel = (key) => {
    setPanelType(!isNetworkPanel);
    // console.log("key", key);
    if (key == '1') {
      setNetwork(undefined);
    } else if (key == '2') {
      setNetwork(controlData);
    }
  };



  const onClick = () => {
    setLoading(true);
    setTimeout(() => setLoading(false), 0);
  };

  const getControlPower = (props) => {
    console.log('拿到的控制权信息', props);
    if (props) {
      setControlData(props);
      setNetwork(props);
    }
  };

  const { TabPane } = Tabs;

  return (
    <>
      <GraphLayout
        leftSpan={13}
        rightSpan={11}
        leftChildren={
          <ProCard style={{ borderRadius: '8px', height: '100vh' }} loading={loading}>
            {/* 防止graphin图标加载滞后 */}
            <div style={{ height: '0px', overflow: 'hidden' }}>
              <span
                style={{
                  fontFamily: 'graphin',
                  transform: 'scale(0)',
                  opacity: 0,
                  fontSize: '1px',
                }}
              >
                &#xe7ce;
              </span>
            </div>
            <EquityGraph
              eid={enterprise.eid}
              network={network}
              onNetworkChange={handleUpdateNetwork}
              date={date}
              holders={holders}
              refresh={onClick}
            />
          </ProCard>
        }
        rightChildren={
          <>
            <ProCard style={{ borderRadius: '8px', height: '100vh' }} bodyStyle={{ padding: '0' }}>
              <Tabs defaultActiveKey="1" centered tabBarGutter="8rem" onChange={onChangePanel}>
                {/* 股权穿透信息 */}
                <TabPane tab={<b style={{ fontSize: '18px' }}>股权穿透信息</b>} key="1">
                  {/*    <p>
              <b>股权网络层数: </b>
              {enterprise.network?.stat?.[0].value}
            </p>
            <p>
              <b>计算耗时:</b> {`${enterprise.network?.stat?.[1].value.toFixed(3) ?? ''}`}
            </p> */}
                  <ProCard
                    bodyStyle={{ padding: '0' }}
                    direction="column"
                    style={{ height: '90vh', overflowY: 'auto', overflowX: 'hidden' }}
                    className="content"
                  >
                    {/* 最终股东 */}
                    <ProCard title={<b style={{ fontSize: '18px' }}>最终股东</b>}>
                      <AvatarList holders={holders} loading={loading} />
                    </ProCard>

                    <ProCard title={<b style={{ fontSize: '18px' }}>直接股东</b>}>
                      <AvatarList holders={equityMsgData} loading={loading} />
                    </ProCard>
                    {/* 饼状图 */}
                    <ProCard
                      title={<b style={{ fontSize: '18px' }}>股权结构分析</b>}
                      style={{ marginTop: '-2em' }}
                    >
                      <List
                        pagination={{
                          showSizeChanger: false,
                          pageSize: 1,
                        }}
                        dataSource={[
                          <DemoPie
                            data={equityStructPieData}
                          />,
                          ...(enterprise.network?.plots || []),
                        ]}
                        renderItem={(plot) =>
                          plot.type === DemoPie ? (
                            <Card>{plot}</Card>
                          ) : (
                            <Card title={plot.title} style={{ minHeight: '20em' }}>
                              <img
                                src={`data:image/png;base64,${plot.img64}`}
                                style={{ maxWidth: '90%', maxHeight: '90' }}
                              />
                            </Card>
                          )
                        }
                      />
                    </ProCard>
                  </ProCard>
                </TabPane>
                {/* 控制权信息 */}
                {/* <TabPane tab={<b style={{ fontSize: '18px' }}>控制权信息</b>} key="2">
                  <ProCard
                    bodyStyle={{ padding: '0' }}
                    direction="column"
                    style={{ height: '90vh', overflow: 'auto', overflowX: false }}
                    className="content"
                  > */}
                {/* 疑似实际控制人  */}
                {/* <ProCard title={<b style={{ fontSize: '18px' }}>疑似实际控制人</b>}>
                      <ControlPowerList
                        holders={holders}
                        getControlPower={getControlPower}
                        enterprise={enterprise}
                      />
                    </ProCard> */}
                {/* 外部关系 */}
                {/* <ProCard title={<b style={{ fontSize: '18px' }}>外部关系</b>}>
                      <RelationList
                        getControlPower={getControlPower}
                        enterprise={enterprise}
                        controlData={controlData}
                      />
                    </ProCard>
                  </ProCard>
                </TabPane> */}
              </Tabs>
            </ProCard>
          </>
        }
      />
    </>

    /* <RankList isShow={!Boolean(enterprise.eid)} onClick={handleClickRank} /> */
  );
};

export default Penetration;
